package chances.epg.data.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;

import chances.epg.commons.utils.CommonUtils;
import chances.epg.data.PageBean;
import chances.epg.entity.content.CategoryItem;

@Service("categoryService")
public class CategoryService extends EpgService {
	

	/**
	 * 
	 * @param categoryCode
	 * @param pageBean
	 * @return
	 */
	@SuppressWarnings("unchecked")
	protected List<CategoryItem> getCategoryItems(Map<String, Object> paramsMap, int start, PageBean pageBean,
			boolean byParent) {
		paramsMap.put("curTime", new Date());
		try {
			if (byParent) {
				return (List<CategoryItem>) this.queryForList("getCategoryItemsByParent", paramsMap, start, pageBean);
			} else {
				return (List<CategoryItem>) this.queryForList("getCategoryItems", paramsMap, start, pageBean);
			}
		} finally {
			paramsMap.clear();
			paramsMap = null;
		}
	}

	public List<CategoryItem> listCategoryItem(String categoryCode, String itemType, int start, PageBean pageBean) {
		List<CategoryItem> categoryItems = null;

		Map<String, Object> params = new HashMap<String, Object>();

		params.put("categoryCode", categoryCode);
		params.put("itemType", itemType);
		categoryItems = this.getCategoryItems(params, start, pageBean, false);
		return categoryItems;

	}
	
	/**
	 * 
	 * @param categoryCode
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<CategoryItem> getCategoryItems(Map<String,Object> paramsMap,boolean byParent){
		paramsMap.put("curTime", new Date());
		
		try{
			if(byParent){
				return (List<CategoryItem>)this.queryForList("getCategoryItemsByParent", paramsMap);
			}else{
			    return (List<CategoryItem>)this.queryForList("getCategoryItems", paramsMap);
			} 
		}finally{
			paramsMap.clear();
			paramsMap = null;
		}
	}


	/**
	 * 按照指定数量随机获取.
	 */
	public List<CategoryItem> queryRandomItem(String categoryCode,String type, int size, boolean byParent) {
		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("categoryCode", categoryCode);
		paramsMap.put("itemType", type);

		List<CategoryItem> result = this.getCategoryItems(paramsMap, byParent);
		if (result.size() <= size) {
			return result;
		} else {
			List<CategoryItem> randomResult = new ArrayList<CategoryItem>();
			int[] randomSequence = CommonUtils.getRandomSequence(result.size());
			for (int i = 0; i < size; i++) {
				randomResult.add(result.get(randomSequence[i]));
			}

			return randomResult;
		}
	}

}
